<template>
  <Navbar>
    <!-- <template v-slot:left></template> -->
    <template v-slot:center>用户注册</template>
  </Navbar>

  <div style="margin-top: 50px">
    <div style="text-align: center">
      <van-image
        width="10rem"
        height="10rem"
        fit="contain"
        src="https://img.yzcdn.cn/vant/cat.jpeg"
      />
    </div>
  </div>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userInfo.name"
        name="name"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="userInfo.email"
        name="email"
        label="电子邮箱"
        placeholder="请输入电子邮箱"
        :rules="[{ required: true, message: '请正确填写电子邮箱' }]"
      />
      <van-field
        v-model="userInfo.password"
        type="password"
        name="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="userInfo.password_confirmation"
        type="password"
        name="password_confirmation"
        label="确认密码"
        placeholder="请再次输入密码"
        :rules="[{ required: true, message: '请填写确认密码' }]"
      />

      <div style="margin: 16px">
        <!-- 这里直接调用vue内部的router -->
        <div class="link-login" @click="$router.push('/login')">
          已有帐号，立即登录
        </div>
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive } from "vue";
import { useRouter } from "vue-router";
import { Image as VanImage, Form, Field, Button, Notify, Toast } from "vant";
import Navbar from "@/components/common/navbar/NavBar.vue";
import { register } from "@/network/user";

export default {
  name: "Register",
  setup() {
    // reactive数据就相当于定义state数据
    const userInfo = reactive({
      name: "",
      email: "",
      password: "",
      password_confirmation: "",
    });

    const router = useRouter();

    const onSubmit = (value) => {
      register(value)
        .then((res) => {
          if (res.status == "201") {
            Toast.success("注册成功");
            // 注册成功之后跳转登录页 且清空密码框内容
            router.push({ path: "/login" });
            userInfo.password = "";
            userInfo.password_confirmation = "";
          }
        })
        .catch(() => {
          Toast.fail("注册失败");
        });
    };
    return {
      userInfo,
      onSubmit,
    };
  },
  components: {
    Navbar,
    [VanImage.name]: VanImage,
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Notify.name]: Notify,
    [Toast.name]: Toast,
  },
};
</script>

<style lang='less'>
.link-login {
  font-size: 14px;
  margin-bottom: 20px;
  color: #42b983;
  float: right;
  margin-right: 20px;
}
</style>